﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;

[CustomEditor(typeof(RInputModuleItem))]
internal class EditRInputModuleItem : Editor
{
    RInputModuleItem editor;

    public void OnEnable()
    {
        editor = target as RInputModuleItem;
    }

    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();


        if (GUILayout.Button("一键重设所有actionName"))
        {
            ResetActions();
        }

        if (GUILayout.Button("执行操作"))
        {
            ResetActionName();
        }

        if (GUILayout.Button("检查配置并补充新增项ID"))
        {
            ReCountActions();
        }
    }


    private void ResetActions()
    {
        var allItems = editor.transform.GetComponentsInChildren<KeyItem>(true).ToList();

        int resetCount = 0;
        foreach (var item in allItems)
        {
            // 仅重设已有actionName的项（空值项也会被处理）
            item.mapping.actionName = Guid.NewGuid().ToString();
            resetCount++;
            Debug.Log($"已重设ID | {item.mapping.actionName}");
            EditorUtility.SetDirty(item);
        }

        Debug.Log($"完成重设，共处理 {resetCount} 个配置项");
        EditorUtility.SetDirty(target);
    }

    private void ReCountActions()
    {
        var allItems = editor.transform.GetComponentsInChildren<KeyItem>(true).ToList();

        // 读取现有配置文件中的actionName
        var existingActionNames = new HashSet<string>();
        string savePath = Path.Combine(Application.persistentDataPath, "keyMappings.json");

        if (File.Exists(savePath))
        {
            try
            {
                string json = File.ReadAllText(savePath);
                var config = JsonUtility.FromJson<DataKeyCollection>(json);
                if (config?.mappings != null)
                {
                    existingActionNames = new HashSet<string>(config.mappings.Select(m => m.actionName));
                    Debug.Log($"已读取配置文件，包含 {existingActionNames.Count} 个已存在的actionName");
                }
            }
            catch (Exception e)
            {
                Debug.LogError($"读取配置文件失败: {e.Message}");
            }
        }
        else
        {
            Debug.Log("配置文件不存在，将为所有项生成新actionName");
        }

        // 为新增项生成actionName（不存在于配置文件且自身actionName为空的项）
        int newCount = 0;
        foreach (var item in allItems)
        {
            // 检查条件：配置中不存在且自身actionName为空
            if (string.IsNullOrEmpty(item.mapping?.actionName) ||
                !existingActionNames.Contains(item.mapping.actionName))
            {
                item.mapping.actionName = Guid.NewGuid().ToString();
                newCount++;
                Debug.Log($"为新增项生成ID | {item.mapping.actionName}");
                EditorUtility.SetDirty(item);
            }
        }

        Debug.Log($"操作完成，共为 {newCount} 个新增项生成了actionName");
        EditorUtility.SetDirty(target);
    }

    private void ResetActionName()
    {
        editor.transform.GetComponentsInChildren<KeyItem>(true)
    .ToList()
    .ForEach(e =>
    {
        e.mapping.actionName = Guid.NewGuid().ToString();
        EditorUtility.SetDirty(e);
    });

        EditorUtility.SetDirty(target);
    }
}
